package com.sinochem.iot.rule.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.sinochem.iot.common.util.BeanHelper;
import com.sinochem.iot.common.vo.TriggerRuleVo;
import com.sinochem.iot.rule.mapper.*;
import com.sinochem.iot.rule.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import springfox.documentation.spring.web.json.Json;

import java.util.*;


@Service
public class TriggerRuleService {

    @Autowired
    private TriggerRuleMapper triggerRuleMapper;
    @Autowired
    private TriggerRuleDetailMapper triggerRuleDetailMapper;

    @Autowired
    private TriggerMapper triggerMapper;
    @Autowired
    private TriggerRuleDetailService triggerRuleDetailService;
    @Autowired
    private RuleActionMapper ruleActionMapper;
    @Autowired
    private RuleConditionMapper ruleConditionMapper;

    /**
     * 通过id获取触发规则
     *
     * @param id
     * @return
     */
    public TriggerRule getTriggerRuleById(Integer id) {
        return triggerRuleMapper.selectByPrimaryKey(id);
    }


    /**
     * 根据触发器id获取触发器规则
     *
     * @param triId
     * @return
     */
    public TriggerRule getTriggerRuleByTriId(Integer triId) {
        TriggerRuleExample triggerRuleExample = new TriggerRuleExample();
        triggerRuleExample.createCriteria().andTriIdEqualTo(triId);
        List<TriggerRule> triggerRuleList = triggerRuleMapper.selectByExample(triggerRuleExample);
        if (triggerRuleList.size() > 0)
            return triggerRuleList.get(0);
        return null;
    }


    /**
     * 根据设备标识获取触发规则
     *
     * @param deviceIdentify
     * @return
     */
    public List<TriggerRule> getTriggerRuleListByDeviceIdentify(String deviceIdentify) {
        TriggerRuleExample triggerRuleExample = new TriggerRuleExample();
        triggerRuleExample.createCriteria().andQueryScopDevLike("%" + deviceIdentify + "%");
        List<TriggerRule> triggerRuleList = triggerRuleMapper.selectByExample(triggerRuleExample);
        return triggerRuleList;
    }

    /**
     * 根据产品id或者属性获取列表
     *
     * @param triggerRule
     * @return
     */
    public List<TriggerRule> getListByProductIdOrProProperty(TriggerRule triggerRule) {
        TriggerRuleExample triggerRuleExample = new TriggerRuleExample();
        TriggerRuleExample.Criteria criteria = triggerRuleExample.createCriteria();
        Integer productId = triggerRule.getQueryScopPro();

        //根据属性获取查询条件列表
        String condition = triggerRule.getQueryCondition();
        List<RuleCondition> ruleConditionList=(List<RuleCondition>)JSON.parseObject(condition);

        List<String> listAttr=new ArrayList<>();
        for (RuleCondition ruleCondition : ruleConditionList) {
            listAttr.add(ruleCondition.getAttr());
        }
        RuleConditionExample ruleConditionExample=new RuleConditionExample();
        ruleConditionExample.createCriteria().andAttrIn(listAttr);
        List<RuleCondition> ruleConditionList1=ruleConditionMapper.selectByExample(ruleConditionExample);
        //获取rule列表
        List<Integer> listRuleId=new ArrayList<>();
        for (RuleCondition ruleCondition : ruleConditionList1) {
            listRuleId.add(ruleCondition.getRuleid());
        }

        if (!StringUtils.isEmpty(productId)) {
            criteria.andQueryScopProEqualTo(productId);
        }
        if (listRuleId.size()>0) {
            criteria.andIdIn(listRuleId);
        }
        List<TriggerRule> triggerRuleList = triggerRuleMapper.selectByExample(triggerRuleExample);
        return triggerRuleList;
    }



    /**
     * 删除触发器规则
     *
     * @param id
     * @return
     */
    public int delTriggerRule(Integer id) {
        return triggerRuleMapper.deleteByPrimaryKey(id);
    }

    /**
     * 添加规则
     *
     * @param triggerRule
     * @return
     */
    @Transactional
    public int addTriggerRule(TriggerRule triggerRule) {

        //关联设备数
        updDevNum(triggerRule);

        //添加规则
        BeanHelper.onInsert(triggerRule);
        int result = triggerRuleMapper.insertSelective(triggerRule);
        //JSONArray json = JSONArray.parseArray(triggerRule.getQueryCondition());
        List<RuleCondition> conditionList=  JSONArray.parseArray(triggerRule.getQueryCondition(), RuleCondition.class);

        for (RuleCondition ruleCondition : conditionList) {
            BeanHelper.onInsert(ruleCondition);
            ruleCondition.setRuleid(result);
            ruleConditionMapper.insertSelective(ruleCondition);
        }
        List<RuleAction> ruleActionList=JSONArray.parseArray(triggerRule.getActions(),RuleAction.class);
        for (RuleAction ruleAction : ruleActionList) {
            BeanHelper.onInsert(ruleAction);
            ruleAction.setRuleid(result);
            ruleActionMapper.insertSelective(ruleAction);
        }

        //添加t_trigger_rule_detail
        triggerRuleDetailService.insertByTriggerRuleStore(triggerRule);

        return result;

    }

    /**
     * 根据触发器id获取触发器规则
     *
     * @param triId
     * @return
     */
    public Map<String, Object> getTriggerRuleAndStoreByTriId(Integer triId) {
        Map<String, Object> map = new HashMap<>();
        //获取规则
        TriggerRuleExample triggerRuleExample = new TriggerRuleExample();
        triggerRuleExample.createCriteria().andTriIdEqualTo(triId);
        List<TriggerRule> triggerRuleList = triggerRuleMapper.selectByExample(triggerRuleExample);
        if (triggerRuleList.size() > 0) {
            TriggerRule triggerRule = triggerRuleList.get(0);
            map.put("rule", triggerRule);

        }
        return map;
    }

    /**
     * 修改规则
     *
     * @param triggerRule
     * @return
     */
    @Transactional
    public int updTriggerRule(TriggerRule triggerRule) {

        //修改关联设备数
        updDevNum(triggerRule);

        //修改规则
        triggerRule.setUpdateTime(new Date());
        triggerRuleMapper.updateByPrimaryKeySelective(triggerRule);

        ruleConditionMapper.deleteByRuleId(triggerRule.getId());
        ruleActionMapper.deleteByRuleId(triggerRule.getId());
        List<RuleCondition> conditionList=  JSONArray.parseArray(triggerRule.getQueryCondition(), RuleCondition.class);
        List<RuleAction> ruleActionList=JSONArray.parseArray(triggerRule.getActions(),RuleAction.class);

        for (RuleCondition ruleCondition : conditionList) {
            BeanHelper.onInsert(ruleCondition);
            ruleConditionMapper.insertSelective(ruleCondition);
        }

        for (RuleAction ruleAction : ruleActionList) {
            BeanHelper.onInsert(ruleAction);
            ruleActionMapper.insertSelective(ruleAction);
        }
        //添加t_trigger_rule_detail
        triggerRuleDetailService.insertByTriggerRuleStore(triggerRule);
        return 1;
    }

    //修改关联设备数
    private void updDevNum(TriggerRule triggerRule) {
        int devCount = 1;
        String queryScopeDev = triggerRule.getQueryScopDev();
        if (queryScopeDev.indexOf(",") > 0)
            devCount = queryScopeDev.split(",").length;
        Trigger trigger = new Trigger();
        trigger.setId(triggerRule.getTriId());
        trigger.setDeviceCount(devCount);
        triggerMapper.updateByPrimaryKeySelective(trigger);
    }


}
